package com.corticon.dialogs.dao.hibernate;

import static org.hibernate.criterion.Restrictions.*;

import java.util.List;

import org.hibernate.Criteria;

import org.springframework.stereotype.Repository;

import com.corticon.dialogs.dao.MessageDAO;
import com.corticon.dialogs.model.Message;

@Repository("messageDAO")
public class MessageHibernateDAO extends GenericHibernateDAO<Message, Long> implements MessageDAO {

    @Override
    public String getMessage(String fieldName, String messageKey, String defaultMessage,
        String local) {
        defaultMessage = defaultMessage == "" ? "Default Message!" : defaultMessage;
        String querySql = "select * from Message where messagekey='" + messageKey + "'";

        /**
        if (local != null && !local.equals("")){
        querySql += " and language.code='"+local+"'";
        }
         */
        List messages = this.findBySQLQuery(querySql);
        if (messages.size() >= 1 && messages.get(0) != null) {
            Object[] msg = (Object[]) messages.get(0);
            String msgInfo = msg[2].toString();
            msgInfo = msgInfo.replace("{0}", fieldName);
            return msgInfo;
        } else {
            return defaultMessage;
        }
    }

    @Override
    public Message findByKey(String key) {
        Criteria criteria = getBaseCriteria();
        criteria.add(eq("key", key));
        return (Message) criteria.uniqueResult();
    }
}